<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\CommunityShare;
use App\Models\CommunityInteraction;
use Illuminate\Http\Request;

class CommunityShareController extends Controller
{
    /**
     * 获取社区分享列表
     */
    public function index(Request $request)
    {
        try {
            // 验证请求参数
            $request->validate([
                'page' => 'nullable|integer|min:1',
                'per_page' => 'nullable|integer|min:1|max:100',
                'share_type' => 'nullable|string|in:achievement,experience,question'
            ]);

            // 构建查询
            $query = CommunityShare::with(['user'])
                ->where('is_hidden', false);

            // 如果有share_type参数，但数据库中没有这个字段，我们暂时忽略它
            // 后续可以通过添加数据库字段或使用tags来实现分类
            
            // 排序
            $query->orderBy('created_at', 'desc');

            // 分页参数
            $perPage = $request->get('per_page', 20);
            $page = $request->get('page', 1);

            // 执行分页查询
            $shares = $query->paginate($perPage, ['*'], 'page', $page);

            // 为每个分享添加用户互动状态
            $userId = auth()->id();
            $sharesData = $shares->items();
            
            foreach ($sharesData as $share) {
                $share->is_liked = $userId ? $share->isLikedBy($userId) : false;
                $share->is_bookmarked = $userId ? $share->isBookmarkedBy($userId) : false;
            }

            return response()->json([
                'success' => true,
                'data' => [
                    'current_page' => $shares->currentPage(),
                    'data' => $sharesData,
                    'last_page' => $shares->lastPage(),
                    'total' => $shares->total(),
                    'per_page' => $shares->perPage(),
                    'from' => $shares->firstItem(),
                    'to' => $shares->lastItem(),
                    'first_page_url' => $shares->url(1),
                    'last_page_url' => $shares->url($shares->lastPage()),
                    'next_page_url' => $shares->nextPageUrl(),
                    'prev_page_url' => $shares->previousPageUrl(),
                    'path' => $shares->path()
                ],
                'message' => '获取分享列表成功',
                'timestamp' => now()->toISOString()
            ]);
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'error' => [
                    'message' => '请求参数无效',
                    'details' => $e->errors()
                ]
            ], 422);
        } catch (\Exception $e) {
            \Log::error('CommunityShareController@index error: ' . $e->getMessage());
            \Log::error('Stack trace: ' . $e->getTraceAsString());
            
            return response()->json([
                'success' => false,
                'error' => [
                    'message' => '获取分享列表失败',
                    'details' => config('app.debug') ? $e->getMessage() : '服务器内部错误'
                ]
            ], 500);
        }
    }

    /**
     * 创建新的分享
     */
    public function store(Request $request)
    {
        try {
            $request->validate([
                'title' => 'nullable|string|max:200',
                'content' => 'required|string|max:1000',
                'screenshot_url' => 'nullable|string|max:500',
                'tags' => 'nullable|string'
            ]);

            $share = CommunityShare::create([
                'user_id' => auth()->id(),
                'title' => $request->title,
                'content' => $request->content,
                'screenshot_url' => $request->screenshot_url,
                'tags' => $request->tags,
                'is_hidden' => false
            ]);

            $share->load('user');

            return $this->success($share, '分享创建成功', 201);
        } catch (\Exception $e) {
            \Log::error('创建分享失败: ' . $e->getMessage());
            return $this->error('创建分享失败', 500);
        }
    }

    /**
     * 与分享互动（点赞、评论等）
     */
    public function interact(Request $request, CommunityShare $share)
    {
        $request->validate([
            'interaction_type' => 'required|in:like,comment',
            'content' => 'required_if:interaction_type,comment|string|max:500'
        ]);

        $interaction = CommunityInteraction::updateOrCreate(
            [
                'user_id' => auth()->id(),
                'community_share_id' => $share->id,
                'interaction_type' => $request->interaction_type
            ],
            [
                'content' => $request->get('content')
            ]
        );

        return response()->json([
            'interaction' => $interaction,
            'message' => 'Interaction recorded'
        ]);
    }

    /**
     * 获取分享的评论
     */
    public function comments(CommunityShare $share)
    {
        $comments = CommunityInteraction::with('user')
            ->where('community_share_id', $share->id)
            ->where('interaction_type', 'comment')
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json($comments);
    }
}